# -*- coding: UTF-8 -*-
# 34461A 万用表
import pyvisa
from pyvisa.constants import *
import xlwt
import time
import os

class multimeter:
    # 打开万用表
    def __init__(self, count):
        rm = pyvisa.ResourceManager()
        tupl = rm.list_resources()
        if len(tupl) <= 0:
            print("can not find port !")
        else:
            self.res = rm.open_resource(tupl[count], AccessModes.no_lock, 3000, None)

    def DCV(self, volt_value=100, count=10, delay=100):
        """
            @:param volt_value 100mv~1000V  测试电压值
            @:param count 1~100  样本统计数量
            @:param delay 延迟100ms
        """

        if volt_value < 0 or delay < 0:
            raise Exception(" DCV test volt_value or delay Not less than zero")
        try:
            time_string = str(time.strftime('%Y%m%d%H%M%S') + '直流电压测试')
            dev_string = ('./' + time_string + '.xls').decode('utf-8')
            path = os.path.abspath(dev_string)
            book = xlwt.Workbook(encoding='utf-8', style_compression=0)
            sheet = book.add_sheet("直流电压测试日志表", cell_overwrite_ok=True)
            sheet.write(0, 0, '直流电压值(V)')
            sheet.write(1, 0, '最大电压值(V)')
            sheet.write(2, 0, '最小电压值(V)')
            sheet.write(3, 0, '平均电压值(V)')
            self.res.write('SYSTem:REM')
            self.res.write('SYSTem:PRESet')
            self.res.write('*CLS')
            self.res.write('SENSe:VOLT:DC %f' % volt_value)
            self.res.write(':SAMP:COUN %d' % count)
            self.res.write(':TRIG:DELay %f' % (delay / 1000.0))
            self.res.write('READ?')
            time.sleep(count * 0.5)
            dcv_res = self.res.read().encode('utf-8')
            dcv_result = dcv_res.split(',')
            for index in dcv_result:
                row = 0
                while (row < count):
                    sheet.write(0, row + 1, index)
                    row = row + 1
            Sum = 0
            for index in dcv_result:
                Sum = float(index) + Sum
            avg_value = Sum / len(dcv_result)
            max_value = max(dcv_result)
            min_value = min(dcv_result)
            sheet.write(1, 1, max_value)
            sheet.write(2, 1, min_value)
            sheet.write(3, 1, avg_value)
            book.save(path)
            print("直流电电压测试样本数量=%d 最大值=%s 最小值=%s 平均值=%f" % (count, max_value, min_value, avg_value))
            return count, max_value, min_value, avg_value
        except ValueError as  v:
            print (v)
        finally:
            self.res.write('*CLS')
            self.res.write('SYSTem:LOCal')

    # test DCI 10A range ,100uA resolution
    def DCI(self, dampere_range=Config().get_dampere_range(), dampere_res=Config().get_dampere_res(),
            count=Config().get_count(), delay=Config().get_delay()):
        """
        :param ampere_max:10A   测试电流值
        :param ampere_min:0.0001A 测试电流值
        :param count: 1~100  样本统计数量
        :param delay:延迟100ms
        :return:
        """
        if dampere_range < 0 or dampere_res < 0:
            raise Exception("DCI test volt_value or count Not less than zero"), dampere_range, dampere_res
        try:
            time_string = str(time.strftime('%Y%m%d%H%M%S') + '直流电流测试')
            dev_string = ('./' + time_string + '.xls').decode('utf-8')
            path = os.path.abspath(dev_string)
            book = xlwt.Workbook(encoding='utf-8', style_compression=0)
            sheet = book.add_sheet("直流电流测试日志表", cell_overwrite_ok=True)
            sheet.write(0, 0, '直流电流值(A)')
            sheet.write(1, 0, '最大电流值(A)')
            sheet.write(2, 0, '最小电流值(A)')
            sheet.write(3, 0, '平均电流值(A)')
            res = self.ResourceManager()
            res.write('SYSTem:REM')
            res.write('SYSTem:PRESet')
            res.write('*CLS')
            res.write('CONF:CURR:DC %f,%f' % (dampere_range, dampere_res))
            res.write('SAMP:COUN %d' % count)
            res.write('TRIG:DELay %f' % (delay / 1000.0))
            time.sleep(count * 0.5)
            res.write('READ?')
            dcv_res = res.read().encode('utf-8')
            dcv_result = dcv_res.split(',')
            for index in dcv_result:
                row = 0
                while (row < count):
                    sheet.write(0, row + 1, index)
                    row = row + 1
            Sum = 0
            for index in dcv_result:
                Sum = float(index) + Sum
            avg_value = Sum / len(dcv_result)
            max_value = max(dcv_result)
            min_value = min(dcv_result)
            sheet.write(1, 1, max_value)
            sheet.write(2, 1, min_value)
            sheet.write(3, 1, avg_value)
            book.save(path)
            print("直流电电流测试样本数量=%d 最大值=%s 最小值=%s 平均值=%f" % (count, max_value, min_value, avg_value))

        except ValueError as v:
            print (v)
        finally:
            res.write('*CLS')
            res.write('SYSTem:LOCal')

    # test OHM 100ohm range ,100uOhm resolution
    def OHM(self, ohm_max=Config().get_ohm_max(), ohm_min=Config().get_ohm_min(), count=Config().get_count(),
            delay=Config().get_delay()):
        """
            @:param ohm_max 电阻最大值 默认100欧姆
            @:param ohm_min 电阻最小值,默认0.0001欧
            @:param count 1~100  样本统计数量
            @:param delay 延迟100ms
        """

        if ohm_max < 0 or ohm_min < 0:
            raise Exception("OHM test ohm_max or ohm_min Not less than zero"), ohm_max, ohm_min
        try:
            time_string = str(time.strftime('%Y%m%d%H%M%S') + '电阻测试')
            dev_string = ('./' + time_string + '.xls').decode('utf-8')
            path = os.path.abspath(dev_string)
            book = xlwt.Workbook(encoding='utf-8', style_compression=0)
            sheet = book.add_sheet("电阻测试日志表", cell_overwrite_ok=True)
            sheet.write(0, 0, '电阻测试值(A)')
            sheet.write(1, 0, '最大电阻值(A)')
            sheet.write(2, 0, '最小电阻值(A)')
            sheet.write(3, 0, '平均电阻值(A)')
            res = self.ResourceManager()
            res.write('SYSTem:REM')
            res.write('SYSTem:PRESet')
            res.write('*CLS')
            res_range = 'CONF:RES {0}, {1}'.format(ohm_max, ohm_min)
            res.write(res_range)
            res.write('SAMP:COUN %d' % count)
            res.write('TRIG:DELay %f' % (delay / 1000.0))
            time.sleep(count * 0.5)
            res.write('READ?')
            ohm_value = res.read().encode('utf-8')
            ohm_result = ohm_value.split(',')
            for index in ohm_result:
                row = 0
                while (row < count):
                    sheet.write(0, row + 1, index)
                    row = row + 1
            Sum = 0
            for index in ohm_result:
                Sum = float(index) + Sum
            avg_value = Sum / len(ohm_result)
            max_value = max(ohm_result)
            min_value = min(ohm_result)
            sheet.write(1, 1, max_value)
            sheet.write(2, 1, min_value)
            sheet.write(3, 1, avg_value)
            book.save(path)
            print("电阻测试样本数量=%d 最大值=%s 最小值=%s 平均值=%f" % (count, max_value, min_value, avg_value))
        except ValueError as v:
            print (v)
        finally:
            res.write('*CLS')
            res.write('SYSTem:LOCal')
            # test Temperature reading with  a 5K thermistor

    def Temperature(self, count=Config().get_count(), delay=Config().get_delay()):
            """
            :param Temprange: 最大温度 5000
            :param count:  1~100  样本统计数量
            :param delay:  延迟100ms
            :return:
            """
            try:
                time_string = str(time.strftime('%Y%m%d%H%M%S') + '温度测试')
                dev_string = ('./' + time_string + '.xls').decode('utf-8')
                path = os.path.abspath(dev_string)
                book = xlwt.Workbook(encoding='utf-8', style_compression=0)
                sheet = book.add_sheet("温度测试日志表", cell_overwrite_ok=True)
                sheet.write(0, 0, '温度测试值(A)')
                sheet.write(1, 0, '最大温度值(A)')
                sheet.write(2, 0, '最小温度值(A)')
                sheet.write(3, 0, '平均温度值(A)')
                res = self.ResourceManager()
                res.write('SYSTem:REM')
                res.write('SYSTem:PRESet')
                res.write('*CLS')
                res.write('CONF:Temp THER,5000')
                res.write('UNIT:TEMP F')
                res.write('MEAS:TEMP? FRTD')
                res.write('SAMP:COUN %d' % count)
                res.write('TRIG:DELay %f' % (delay / 1000.0))
                time.sleep(count * 0.5)
                res.write('READ?')
                freq_value = res.read()
                freq_result = freq_value.split(',')
                for index in freq_result:
                    row = 0
                    while (row < count):
                        sheet.write(0, row + 1, index)
                        row = row + 1
                Sum = 0
                for index in freq_result:
                    Sum = float(index) + Sum
                avg_value = Sum / len(freq_result)
                max_value = max(freq_result)
                min_value = min(freq_result)
                sheet.write(1, 1, max_value)
                sheet.write(2, 1, min_value)
                sheet.write(3, 1, avg_value)
                book.save(path)
                print("温度测试样本数量=%d 最大值=%s 最小值=%s 平均值=%f" % (count, max_value, min_value, avg_value))

            finally:
                res.write('*CLS')
                res.write('SYSTem:LOCal')